package dao

import (
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"kf/models/entity"
	"time"
)

type IpBlackDao struct {
	DB  *gorm.DB
	Log *zap.Logger
}

func (ipBlackDao *IpBlackDao) CreateIpblack(ip string, kefuId string) uint {
	black := &entity.Ipblack{
		IP:       ip,
		KefuId:   kefuId,
		CreateAt: time.Now(),
	}
	ipBlackDao.DB.Create(black)
	return black.ID
}

// 删除黑名单ip
func (ipBlackDao *IpBlackDao) DeleteIpBlackByIp(ip string) {
	ipBlackDao.DB.Where("ip = ?", ip).Delete(&entity.Ipblack{})
}
func (ipBlackDao *IpBlackDao) FindIp(ip string) entity.Ipblack {
	var ipblack entity.Ipblack
	result := ipBlackDao.DB.Where("ip = ?", ip).First(&ipblack)
	if result.Error != nil && errors.Is(result.Error, gorm.ErrRecordNotFound) {
		// 处理未找到记录的情况
		ipBlackDao.Log.Error("黑名单ip未找到", zap.String("ip", ip))
	}
	return ipblack
}

// 根据客服的id查找黑名单ip
func (ipBlackDao *IpBlackDao) FindIpsByKefuId(id string) []entity.IpBlackPageVo {
	var ipblack []entity.Ipblack
	ipBlackDao.DB.Where("kefu_id = ?", id).Find(&ipblack)
	var ipVos []entity.IpBlackPageVo
	for _, v := range ipblack {
		vo := entity.IpBlackPageVo{
			ID:       v.ID,
			IP:       v.IP,
			KefuId:   v.KefuId,
			KefuName: "",
			CreateAt: v.CreateAt.Format(time.DateTime),
		}
		ipVos = append(ipVos, vo)
	}
	return ipVos
}

// 分页查询黑名单ip
func (ipBlackDao *IpBlackDao) PageIps(query any, args []any, page uint, pagesize uint) []entity.Ipblack {
	offset := (page - 1) * pagesize
	if offset < 0 {
		offset = 0
	}
	var ipblacks []entity.Ipblack
	if query != nil {
		ipBlackDao.DB.Where(query, args...).Offset(int(offset)).Limit(int(pagesize)).Find(&ipblacks)
	} else {
		ipBlackDao.DB.Offset(int(offset)).Limit(int(pagesize)).Find(&ipblacks)
	}
	return ipblacks
}

// 查询条数
func (ipBlackDao *IpBlackDao) CountIps(query any, args []any) int64 {
	var count int64
	if query != nil {
		ipBlackDao.DB.Model(&entity.Ipblack{}).Where(query, args...).Count(&count)
	} else {
		ipBlackDao.DB.Model(&entity.Ipblack{}).Count(&count)
	}
	return count
}

func (ipBlackDao *IpBlackDao) PageKeFuIps(query any, args []any, page uint, pagesize uint) []entity.IpBlackPage {
	offset := (page - 1) * pagesize
	if offset < 0 {
		offset = 0
	}
	var ipblacks []entity.IpBlackPage
	tx := ipBlackDao.DB.
		Select("ipblack.id,ipblack.ip,ipblack.create_at,ipblack.kefu_id,sys_user.username as kefu_name").
		Table("ipblack").
		Joins("left join sys_user on ipblack.kefu_id=sys_user.id")
	if query != nil {
		tx.Where(query, args...)
	}
	tx.Offset(int(offset)).Limit(int(pagesize)).Find(&ipblacks)
	return ipblacks
}
